import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Radio,
  RadioGroup,
  RangePicker,
  Select,
  Space,
  Spin
} from 'ant-design-vue'
import moment, { Moment } from 'moment'
import { defineComponent, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { orderApi } from '@/apis'
import {
  ActivityItem,
  CityItem,
  GetActivityBrandAreaRes
} from '@/apis/orderTypes'
import { useBack } from '@/hooks'

import {
  activityTypeOptions,
  brandIdOptions,
  dimensionOptions,
  peopleTypeOptions,
  restaurantTypeOptions
} from '../../constants'
import PeopleList from './hook/peopleList'
import ProductList from './hook/productList'
import ShopSelectList from './hook/shopSelectList'

export default defineComponent({
  name: 'DcCreateLimit',
  setup() {
    const loading = ref(false)
    const { handleCancel } = useBack('refreshTimeLimitList')
    const route = useRoute()
    const activityData = ref({} as ActivityItem)
    const peopleSelectList = ref([] as any[])
    const productUploadList = ref([] as any[])
    const restaurantList = ref([] as any[])
    const onlyCoin = ref(true)
    const provinceList = ref([] as any[])
    const cityList = ref([] as any[])
    const selectTime = ref([] as any[])
    const shopSelectList = ref<ComponentRef>({})
    const productList = ref<ComponentRef>({})
    const peopleList = ref<ComponentRef>({})
    const firstChangeProvice = ref(true)

    const rulesRef = ref({
      activityName: [
        { required: true, message: '请输入活动名称', trigger: 'blur' }
      ],
      activityType: [{ required: true, message: '请选择活动类型' }],
      brandId: [{ required: true, message: '请选择商品供应商' }],
      peopleType: [{ required: true, message: '请选择适用人群' }],
      status: [{ required: true, message: '请选择状态' }],
      weight: [{ required: true, message: '请输入权重', trigger: 'blur' }]
    } as FormRules)

    const disabledDate = (current: Moment) => {
      return current && current < moment().startOf('day')
    }

    onMounted(() => {
      if (route.query.id) {
        getDetail()
      } else {
        activityData.value.activityType = 1
        activityData.value.restaurantType = 0
        activityData.value.peopleType = 0
        activityData.value.status = 1
        activityData.value.activityDimension = 0
      }
    })

    async function getDetail() {
      try {
        loading.value = true
        const res = await orderApi.getActivityDetail(route.query.id)
        peopleSelectList.value = res.people
        productUploadList.value = res.products
        restaurantList.value = res.restaurants
        activityData.value.activityName = res.activityName
        activityData.value.activityType = res.activityType
        activityData.value.brandId = res.brandId
        activityData.value.cashDiscount = res.cashDiscount
        activityData.value.city = res.city
        activityData.value.id = res.id
        activityData.value.payGoldBean = res.payGoldBean
        activityData.value.payType = res.payType
        activityData.value.people = (res.people ? res.people : []).map(val => {
          return val.id
        })
        activityData.value.peopleType = res.peopleType
        activityData.value.province = res.province
        activityData.value.restaurantType = res.restaurantType
        activityData.value.restaurants = (
          res.restaurants ? res.restaurants : []
        ).map(val => {
          return val.id
        })
        activityData.value.status = res.status
        activityData.value.weight = res.weight
        activityData.value.activityDimension = res.activityDimension
        activityData.value.products = res.products
        selectTime.value = res.activityStartTime
          ? [moment(res.activityStartTime), moment(res.activityEndTime)]
          : []

        if (res.activityDimension == 1) {
          productList.value!.handleRefresh(productUploadList.value)
        }
        if (res.peopleType == 1) {
          peopleList.value!.handleRefresh(peopleSelectList.value)
        }
        getBrandArea()
      } finally {
        loading.value = false
      }
    }

    /** 供应商改变刷新地区、门店列表 */
    function handleBrandChange() {
      getBrandArea()
      if (activityData.value.activityDimension == 1) {
        handleClearProduct()
      } else {
        handleClearRestaurant()
      }
    }

    async function getBrandArea() {
      try {
        const res = await orderApi.getActivityBrandArea(
          activityData.value.brandId
        )
        provinceList.value = formatProvince(res)
        if (route.query.id && activityData.value.province) {
          handleProvinceChange(activityData.value.province, true)
        }
      } finally {
      }
    }

    /** 选择省、市刷新门店列表 */
    function formatProvince(array: GetActivityBrandAreaRes) {
      const data = array.map(val => {
        const children = formatCity(val.cities)
        return {
          label: val.provinceName,
          value: val.provinceName,
          children: children
        }
      })
      return data
    }

    function handleProvinceChange(value, disclean) {
      if (value) {
        const provinceData = provinceList.value.filter(val => {
          return val.value == value
        })
        cityList.value = provinceData[0] ? provinceData[0].children : []
        if (!firstChangeProvice.value) {
          activityData.value.city = ''
          firstChangeProvice.value = false
        }
      }
      if (!disclean) {
        handleClearRestaurant()
      }
    }

    function formatCity(array: Array<CityItem>) {
      const cityList = array.map(val => {
        return { label: val.cityName, value: val.cityName }
      })
      return cityList
    }

    /** 选择门店 */
    function handleShopSelect(val) {
      activityData.value.restaurants = val
    }

    /** 上传指定人群 */
    function handlePeopleListCallback(val) {
      activityData.value.people = val
    }

    /** 上传商品 */
    function handleProductCallback(val) {
      activityData.value.products = val
    }

    /** 选择变更清空门店 */
    function handleClearRestaurant() {
      activityData.value.restaurants = []
      restaurantList.value = []
      shopSelectList.value!.handleCleanData()
    }

    /** 清空商品 */
    function handleClearProduct() {
      activityData.value.products = []
      productUploadList.value = []
      productList.value!.handleClearData()
    }

    /** 维度变化 */
    function handleDimensionChange() {
      activityData.value.restaurants = []
      restaurantList.value = []
      activityData.value.products = []
      productUploadList.value = []
    }

    async function handleCreateActivity() {
      for (const i in activityData.value) {
        try {
          activityData.value[i] = activityData.value[i].trim()
        } catch {}
      }

      if (!activityData.value.activityName) {
        message.warning('请输入活动名称')
        return
      }

      activityData.value.activityStartTime =
        selectTime.value.length > 0 ? selectTime.value[0].format('x') : null
      activityData.value.activityEndTime =
        selectTime.value.length > 1 ? selectTime.value[1].format('x') : null

      if (!activityData.value.brandId) {
        message.warning('请选择商品供应商')
        return
      }

      if (
        activityData.value.restaurantType == 1 &&
        activityData.value.activityDimension == 0
      ) {
        if (activityData.value.restaurants.length == 0) {
          message.warning('请选择门店')
          return
        }
      }

      if (activityData.value.peopleType == 1) {
        if (
          !activityData.value.people ||
          activityData.value.people.length > 0
        ) {
          message.warning('请上传指定人群')
          return
        }
      } else {
        activityData.value.people = []
      }
      if (
        activityData.value.activityType != 1 &&
        !activityData.value.payGoldBean
      ) {
        message.warning('请输入折扣')
        return
      }
      if (
        activityData.value.activityDimension == 1 &&
        activityData.value.products.length == 0
      ) {
        message.warning('请选择商品')
        return
      }
      if (!activityData.value.weight) {
        message.warning('请输入权重')
        return
      }
      if (activityData.value.weight == 0) {
        message.warning('清数大于0的整数')
        return
      }
      if (activityData.value.activityType == 1) {
        activityData.value.payType = 0
      } else {
        activityData.value.payType = 1
      }

      if ([3, 4].includes(activityData.value.activityType)) {
        activityData.value.cashDiscount = activityData.value.payGoldBean
      } else {
        // @ts-ignore
        activityData.value.cashDiscount = null
      }

      if (route.query.id) {
        await orderApi.activityEdit(activityData.value)
        message.success('编辑成功')
      } else {
        await orderApi.activityAdd(activityData.value)
        message.success('创建成功')
      }
      handleCancel()
    }

    return {
      loading,
      onlyCoin,
      activityData,
      peopleSelectList,
      productUploadList,
      restaurantList,
      shopSelectList,
      productList,
      peopleList,
      provinceList,
      cityList,
      rulesRef,
      selectTime,
      disabledDate,
      handleCancel,
      handleBrandChange,
      handleProvinceChange,
      handleShopSelect,
      handlePeopleListCallback,
      handleProductCallback,
      handleCreateActivity,
      handleClearRestaurant,
      handleDimensionChange
    }
  },
  render() {
    return (
      <div>
        <Spin spinning={this.loading}>
          <h3 style={{ marginLeft: '30px' }}>
            {this.$route.query.id ? '编辑限时活动' : '新增限时活动'}
          </h3>
          <Form labelCol={{ span: 2 }}>
            <FormItem label="活动名称：" rules={this.rulesRef.activityName}>
              <Input
                maxlength={60}
                v-model:value={this.activityData.activityName}
                placeholder="请输入"
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="活动类型：" rules={this.rulesRef.activityType}>
              <RadioGroup v-model:value={this.activityData.activityType}>
                {activityTypeOptions.map(val => (
                  <Radio value={val.value}>{val.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>
            <FormItem label="活动期限：">
              <RangePicker
                disabledDate={this.disabledDate}
                v-model:value={this.selectTime}
                showTime={{
                  hideDisabledOptions: true,
                  defaultValue: [
                    moment('00:00:00', 'HH:mm:ss'),
                    moment('23:59:59', 'HH:mm:ss')
                  ]
                }}
                format={'YYYY-MM-DD HH:mm:ss'}
                separator={'至'}
                style={{ width: '400px' }}
              />
            </FormItem>
            <FormItem label="商品供应商：" rules={this.rulesRef.brandId}>
              <RadioGroup
                v-model:value={this.activityData.brandId}
                onChange={this.handleBrandChange}
              >
                {brandIdOptions.map(val => (
                  <Radio value={val.value}>{val.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>
            <FormItem label="活动区域：">
              <Space>
                <Select
                  style={{ width: '120px' }}
                  placeholder="请选择省"
                  v-model:value={this.activityData.province}
                  options={this.provinceList}
                  allowClear={true}
                  onChange={() =>
                    this.handleProvinceChange(this.activityData.province, false)
                  }
                />
                <Select
                  style={{ width: '120px' }}
                  placeholder="请选择市"
                  v-model:value={this.activityData.city}
                  options={this.cityList}
                  allowClear={true}
                  onChange={this.handleClearRestaurant}
                />
              </Space>
            </FormItem>
            <FormItem label="活动维度">
              <RadioGroup
                v-model:value={this.activityData.activityDimension}
                onChange={this.handleDimensionChange}
              >
                {dimensionOptions.map(val => (
                  <Radio value={val.value}>{val.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>
            {this.activityData.activityDimension == 0 ? (
              <div style={{ marginLeft: '8.35%' }}>
                <FormItem>
                  <RadioGroup v-model:value={this.activityData.restaurantType}>
                    {restaurantTypeOptions.map(val => (
                      <Radio value={val.value}>{val.label}</Radio>
                    ))}
                  </RadioGroup>
                </FormItem>
                <FormItem v-show={this.activityData.restaurantType == 1}>
                  <ShopSelectList
                    ref="shopSelectList"
                    restaurants={this.restaurantList}
                    brandId={this.activityData.brandId ?? 0}
                    province={
                      this.activityData.province
                        ? this.activityData.province
                        : ''
                    }
                    city={this.activityData.city ? this.activityData.city : ''}
                    onDataCallback={this.handleShopSelect}
                  />
                </FormItem>
              </div>
            ) : (
              <div style={{ marginLeft: '8.35%' }}>
                <FormItem>
                  <ProductList
                    ref="productList"
                    brandId={this.activityData.brandId ?? 0}
                    onDataCallback={this.handleProductCallback}
                  />
                </FormItem>
              </div>
            )}
            <FormItem label="适用人群：" rules={this.rulesRef.peopleType}>
              <RadioGroup v-model:value={this.activityData.peopleType}>
                {peopleTypeOptions.map(val => (
                  <Radio value={val.value}>{val.label}</Radio>
                ))}
              </RadioGroup>
            </FormItem>
            <FormItem v-show={this.activityData.peopleType == 1}>
              <PeopleList
                ref="peopleList"
                peoples={this.peopleSelectList ? this.peopleSelectList : []}
                onDataCallback={this.handlePeopleListCallback}
                style={{ marginLeft: '8.35%' }}
              />
            </FormItem>
            <FormItem label="支付设置：">
              {this.activityData.activityType != 1 ? (
                <div>
                  <InputNumber
                    v-model:value={this.activityData.payGoldBean}
                    placeholder="请输入折扣"
                    min={0}
                    max={10}
                    precision={2}
                    style={{ width: '300px' }}
                  />
                  {` 折`}
                </div>
              ) : (
                <Radio v-model:checked={this.onlyCoin}>纯金豆支付</Radio>
              )}
            </FormItem>
            <FormItem label="权重：" rules={this.rulesRef.weight}>
              <InputNumber
                placeholder="请输入"
                v-model:value={this.activityData.weight}
                min={0}
                precision={0}
                style={{ width: '300px' }}
              />
            </FormItem>
            <FormItem label="状态：" rules={this.rulesRef.status}>
              <RadioGroup v-model:value={this.activityData.status}>
                <Radio value={1}>启用</Radio>
                <Radio value={0}>禁用</Radio>
              </RadioGroup>
            </FormItem>
            <FormItem>
              <Button
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.handleCancel}
              >
                取消
              </Button>
              <Button
                type="primary"
                style={{ marginTop: '30px', marginLeft: '90px' }}
                onClick={this.handleCreateActivity}
              >
                确定
              </Button>
            </FormItem>
          </Form>
        </Spin>
      </div>
    )
  }
})
